package com.whnk.attendance.service.impl;

import com.whnk.attendance.api.vo.MonthEmpStatisBatchQueryVo;
import com.whnk.attendance.constant.AttendanceConstants;
import com.whnk.attendance.domain.PmSignInfo;
import com.whnk.attendance.mapper.PmSignInfoMapper;
import com.whnk.attendance.service.IMonthEmpStatisService;
import com.whnk.attendance.service.IPmSignInfoService;
import com.whnk.attendance.vo.*;
import com.whnk.common.core.exception.ServiceException;
import com.whnk.common.core.utils.DateUtils;
import com.whnk.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 项目考勤信息Service业务层处理
 *
 * @author whnk
 * @date 2021-11-17
 */
@Service
public class PmSignInfoServiceImpl implements IPmSignInfoService
{
    private static final Logger log = LoggerFactory.getLogger(PmSignInfoServiceImpl.class);

    @Autowired
    private PmSignInfoMapper pmSignInfoMapper;

    @Autowired
    private IMonthEmpStatisService iMonthEmpStatisService;

    /**
     * 查询项目考勤信息
     *
     * @param signId 项目考勤信息主键
     * @return 项目考勤信息
     */
    @Override
    public PmSignInfo selectPmSignInfoBySignId(Long signId)
    {
        return pmSignInfoMapper.selectPmSignInfoBySignId(signId);
    }

    /**
     * 查询项目考勤信息列表
     *
     * @param pmSignQueryVo 项目考勤信息
     * @return 项目考勤信息
     */
    @Override
    public List<PmSignListVo> selectPmSignInfoList(PmSignQueryVo pmSignQueryVo)
    {
        List<PmSignListVo> pmSignListVos = pmSignInfoMapper.selectPmSignInfoListByQuery(pmSignQueryVo);
        return pmSignListVos;
    }

    /**
     * 新增项目考勤信息
     *
     * @param pmSignInfo 项目考勤信息
     * @return 结果
     */
    @Override
    public int insertPmSignInfo(PmSignInfo pmSignInfo)
    {
        pmSignInfo.setCreateTime(DateUtils.getNowDate());
        return pmSignInfoMapper.insertPmSignInfo(pmSignInfo);
    }

    /**
     * 修改项目考勤信息
     *
     * @param pmSignInfo 项目考勤信息
     * @return 结果
     */
    @Override
    public int updatePmSignInfo(PmSignInfo pmSignInfo)
    {
        pmSignInfo.setUpdateTime(DateUtils.getNowDate());
        return pmSignInfoMapper.updatePmSignInfo(pmSignInfo);
    }

    /**
     * 批量删除项目考勤信息
     *
     * @param signIds 需要删除的项目考勤信息主键
     * @return 结果
     */
    @Override
    public int deletePmSignInfoBySignIds(Long[] signIds)
    {
        return pmSignInfoMapper.deletePmSignInfoBySignIds(signIds);
    }

    /**
     * 删除项目考勤信息信息
     *
     * @param signId 项目考勤信息主键
     * @return 结果
     */
    @Override
    public int deletePmSignInfoBySignId(Long signId)
    {
        return pmSignInfoMapper.deletePmSignInfoBySignId(signId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importPmSignInfo(List<PmSignListImportVo> list, Date signDt,String operName) {
        if (StringUtils.isEmpty(list))
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //覆盖逻辑：根据文件名，把数据库已有数据删除
        String signDtStr = DateUtils.parseDateToStr("yyyy_MM", signDt);
        String signDtStrTwo = DateUtils.parseDateToStr("yyyy-MM", signDt);
        pmSignInfoMapper.deletePmSignInfoBySignDtStr(signDtStr);
        Date now = new Date();
        try{
            List<PmSignInfo> pmSignInfos = new ArrayList<>();
            for (PmSignListImportVo pmSignListImportVo : list)
            {
                PmSignInfo pmSignInfo = new PmSignInfo();
                BeanUtils.copyProperties(pmSignListImportVo, pmSignInfo);
                pmSignInfo.setSignDt(signDt);
                pmSignInfo.setCreateBy(operName);
                pmSignInfo.setCreateTime(now);
                pmSignInfos.add(pmSignInfo);
            }
            int limit = AttendanceConstants.BATCH_INSERT_SIZE;
            int listSize = pmSignInfos.size();
            List<PmSignInfo> newList = new ArrayList<>();
            for (int i = 0; i < listSize; i++) {
                //分批次处理,循环将数据填入载体list
                newList.add(pmSignInfos.get(i));
                //临时存储newList达到要求或者达到最大量,进行批量操作
                if (limit == newList.size() || i == listSize - 1) {
                    //调用批量插入
                    int num = pmSignInfoMapper.insertPmSignInfoBatch(newList);
                    successNum = successNum + num;
                    //每次批量操作后,清空载体list,等待下次的数据填入
                    newList.clear();
                }
            }
            //异步计算每月统计（员工口径）
            MonthEmpStatisBatchQueryVo monthEmpStatisBatchQueryVo = new MonthEmpStatisBatchQueryVo();
            monthEmpStatisBatchQueryVo.setStartMonth(signDtStrTwo);
            monthEmpStatisBatchQueryVo.setEndMonth(signDtStrTwo);
            iMonthEmpStatisService.batchComputerAsync(monthEmpStatisBatchQueryVo);
            successMsg.append("恭喜您，数据导入成功！共 " + successNum + " 条");
            return successMsg.toString();
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            failureMsg.append("很抱歉，导入失败！错误如下：" + ex.getMessage());
            throw new ServiceException(failureMsg.toString());
        }
    }

    @Override
    public List<DailySignListVo> queryDailySignReport(DailySignQueryVo dailySignQueryVo) {
        return pmSignInfoMapper.queryDailySignReport(dailySignQueryVo);
    }
}
